package com.jt.serviceImpl;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.jt.exception.ServiceException;
import com.jt.service.MobileCodeService;
import com.jt.vo.SysResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.JedisCluster;

import java.util.UUID;

/**
 * @author dc
 * @Classname MobileCodeServiceImpl
 * @Date 2020/5/26 9:18
 */
@Service
public class MobileCodeServiceImpl implements MobileCodeService {
    @Autowired
    JedisCluster redis;

    private String templateCode="SMS_190789466";

    private String accessKeyId="LTAI4G2NHZ7MS3UWiFLB9NYc";

    private String accessKeySecret="DRKxSF2M53ZwapLfUBx9irLtBvwblf";

    private String signName="京淘验证";

    @Override
    public SysResult sendMobileCode(String mobile) {
        //随机生成验证码，6位
        String code=String.valueOf(Math.random()*1000000).substring(0,5);
        //生成一个uuid，防止网络攻击
        String uuid= UUID.randomUUID().toString();
        //设置安全码，用于用户绑定
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);
        //设置请求参数
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("Format","json");
        request.putQueryParameter("SignName",signName);
        request.putQueryParameter("SignatureNonce",uuid);
        request.putQueryParameter("TemplateCode",templateCode);
        request.putQueryParameter("TemplateParam","{\"code\":\""+code+"\"}");
        request.putQueryParameter("AccessKeyId",uuid);
        request.putQueryParameter("PhoneNumbers",mobile);
        try {
            CommonResponse response = client.getCommonResponse(request);
            redis.setex("MobileCode",120,code);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("短信发送出错");
        }
        return SysResult.success("已发送");
    }
}
